package com.shujia.flink.sql

import java.time.LocalDateTime

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.table.functions.ScalarFunction
import org.apache.flink.types.Row

object Demo10ProcTIme {
  def main(args: Array[String]): Unit = {
    //创建flink的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //使用blink计划器
      .inStreamingMode() //流模式
      .build()

    /**
      * 创建flink sql 环境
      *
      */

    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE words (
        |  word STRING,
        |  user_action_time AS PROCTIME() -- 声明一个额外的列作为处理时间属性
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'words',
        | 'properties.bootstrap.servers' = 'master:9092',
        | 'properties.group.id' = 'asdasd',
        | 'format' = 'csv',
        | 'csv.field-delimiter' = ',',
        | 'csv.ignore-parse-errors' = 'true',
        | 'scan.startup.mode' = 'earliest-offset'
        |)
        |
      """.stripMargin)


    /**
      * 注册自定义函数
      *
      */
    bsTableEnv.createTemporaryFunction("addTime", new AddTime)


    /**
      * 创建sink表保存数据
      */


    bsTableEnv.executeSql(
      """
        |CREATE TABLE mysql_sink (
        |  word STRING,
        |  window_end TIMESTAMP(3),
        |  c BIGINT,
        |  PRIMARY KEY (word,window_end) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/bigdata',
        |   'table-name' = 'word_window_count',
        |   'username'='root',
        |   'password'='123456'
        |)
        |
        |
      """.stripMargin)

    /**
      * 每隔5秒统计单词的数量
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |insert into mysql_sink
        |select
        | word,
        | addTime(TUMBLE_END(user_action_time, INTERVAL '5' SECOND)) as window_end,
        | count(1) as c
        |from
        | words
        |group by
        | word,
        | TUMBLE(user_action_time, INTERVAL '5' SECOND)
        |
      """.stripMargin)


  }

}


/**
  * flink  自定义函数
  *
  */
class AddTime extends ScalarFunction {
  def eval(time: LocalDateTime): LocalDateTime = {
    //事件增加8小时
    time.plusHours(8)
  }
}